<template>
  <div class="userrecharge-box" style="padding: 10px 0px">
    <div style="margin-bottom: 12px;text-align:center;font-size: 16px;color: #FF5722;">
      很抱歉，您的账户余额不足，请立即充值
    </div>
    <!-- <div class="recharge-tips">
      <img src="assets/safe.png">
      <div class="recharge-words">
        <h5>重要通知</h5>
        <p>1、充值后，如果刷新余额还未到账，请 <a href="/" style="font-weight: bold;color: red;">点我补款</a></p>
        <p>2、订单问题请联系网站客服QQ：<span>{{ contact.frontServiceQQ }}</span>，电话：<span></span>。</p>
        <p>3、请关闭所有弹出窗口杀手之类的功能，否则在线支付将无法继续。</p>
        <p>4、 如:google toolbar,上网助手,alexa toolbar,baidu,等 在开始支付后，不要关闭任何窗口，直到支付成功。</p>
        <p style="color: #72ab78">5、1</p>
      </div>
    </div> -->
    <div class="recharge-form-box" >
      <form class="layui-form" method="post" action="/" autocomplete="off" target="_blank">
        <div class="layui-form-item">
          <div class="layui-form-item">
            <label class="layui-form-label">支付方式</label>
            <div class="layui-input-block choosepay-way">
              <div class="payitems payitems"  v-for="item in chargeList" :key="item.rechargeModeID"
                   :class="onlineRecharge === item.rechargeModeID ? 'payitems payitems-active' : ''"
                   @click="onlineRecharge = item.rechargeModeID">
                <img style="width: auto" :alt="item.rechargeName" :src="item.rechargeImg" />
              </div>

            </div>
          </div>
          <label class="layui-form-label" style="display:inline-block;">充值金额</label>
          <div class="layui-input-inline" style="display: flex;width:70%;">
            <a class="layui-btn layui-btn-sm" rel="pmoney" @click="money=5" href="javascript:;" style="width:50px;">5元</a>
            <a class="layui-btn layui-btn-sm" rel="pmoney" @click="money=10" href="javascript:;" style="width:50px;">10元</a>
            <a class="layui-btn layui-btn-sm" rel="pmoney" @click="money=50" href="javascript:;" style="width:50px;">50元</a>
            <a class="layui-btn layui-btn-sm" rel="pmoney" @click="money=100" href="javascript:;" style="width:50px;">100元</a>
            <el-input style="display:inline-block;margin-left:10px;width:130px;" v-model="money" placeholder="充值金额"></el-input>
          </div>

        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">支付总额</label>
          <div class="layui-input-inline" style="width:300px;">
            <el-input :value="money+'元'" placeholder="充值金额" readonly></el-input>
          </div>
          <div class="layui-form-mid layui-word-aux" style="font-size: 12px;">手续费 <span class="needpoundage">0</span> 元 (默认手续费<span id="needpoundage_show">5</span>%，最低手续费为<span id="needpoundage_show1">0.5</span>元)</div>
        </div>
        <div class="layui-form-item" id="afs_btn" style="display: none;">
          <div class="layui-input-block">
            <div id="captcha"></div>
          </div>
        </div>
        <div class="layui-form-item" id="recharge_btn">
          <label class="layui-form-label" style="display:inline-block;"></label>
          <div class="layui-input-block">
            <el-button @click="doRecharge" type="primary" :disabled="!money">立即充值</el-button>
          </div>
        </div>
      </form>
    </div>
    <el-dialog width="240px" title="扫码支付" :visible.sync="payDialog" append-to-body :before-close="handleClosePayCode">
        <span v-if="codeUrl">
          <img :src="codeUrl" />
        </span>
    </el-dialog>
  </div>
</template>

<script>
import { paySubmit, xmlSyncRequest } from '@/common/utils'
import QRCode from 'qrcode'
const options = {
  errorCorrectionLevel: 'H',
  margin: 1
  // type: 'image/jpeg',
  // quality: 1,
  // color: {
  //   dark: '#010599FF',
  //   light: '#FFBF60FF'
  // }
}
export default {
  // layout: 'webIn',
  // async asyncData({ $axios }) {
  //   const res = await $axios.get('/finance/rechargeMode/getListForClient', {
  //     params: {
  //       rechargeType: 1
  //     }
  //   })
  //   let chargeList = []
  //   if (res.code === 1001 && res.body) {
  //     chargeList = res.body
  //   }
  //   // 联系我们
  //   const a = await $axios.get('/site/onlineService/getFK')
  //   let contact = {}
  //   if (a.code === 1001 && a.body) {
  //     contact = a.body
  //   }
  //   return { chargeList, contact }
  // },
  data() {
    return {
      chargeList:[],
      contact:{},
      cardNo:'',
      addCard : 'addCard',
      active: 'online',
      money: 0,
      codeUrl: null,
      payDialog: false, // 支付弹窗
      qrCode: '', // 二维码地址
      payInterval: null, // 支付的定时器
      payIntervalCount: 0, // 轮询次数
      outTradeNo: '', // 支付订单
      onlineRecharge: '',
      options: [
        {
          value: '1',
          label: '选项1'
        }
      ],
      value: ''
    }
  },
  created() {
    const res = this.$axios.get('/finance/rechargeMode/getListForClient', {
      params: {
        rechargeType: 1
      }
    }).then((res) => {
      this.chargeList = res.body

    });
    const a = this.$axios.get('/site/onlineService/getFK').then((res)=>{
      this.contact = res.body
    })
  },
  methods: {
    async doRecharge() {
      if (this.isLoading) return
      if (this.active === 'online') {
        const money = parseFloat(this.money)
        if (isNaN(money)) {
          return this.$message.error('充值金额输入错误')
        }
        if (money > 100000) {
          return this.$message.error('充值金额超过最大充值金额100000')
        }
        if (!this.onlineRecharge) {
          return this.$message.error('请选择充值支付方式')
        }
        this.$cookies.remove('pay-redirect')
        this.isLoading = true
        // 使用XMLHttpRequest进行同步请求，防止form新打开窗口被浏览器拦截
        const res = xmlSyncRequest(
          this,
          '/finance/rechargeRecord/addRecharge',
          { money, rechargeModeID: this.onlineRecharge }
        )
        if (res.code === 1001 && res.body && res.body.postUrl) {
          paySubmit(res.body)
          setTimeout(() => {
            this.isLoading = false
          }, 1000)
          // 监听支付成功
          clearInterval(this.timer)
          this.timer = setInterval(() => {
            if (this.$cookies.get('pay-redirect')) {
              this.$cookies.remove('pay-redirect')
              location.href = '/main?pay=1'
            }
          }, 1000)
        } else if (res.code === 1001 && res.body.qr_code) {
          // 有二维码，当面付
          this.qrCode = res.body.qr_code
          console.log(this.qrCode)
          this.codeUrl = await QRCode.toDataURL(this.qrCode, options)
          this.outTradeNo = res.body.out_trade_no
          this.payDialog = true
          // 在这里轮询
          this.payInterval = setInterval(() => {
            this.$axios
              .get('/finance/rechargeRecord/queryPayStateFk', {
                params: {
                  paySn: this.outTradeNo
                }
              })
              .then((payRes) => {
                if (payRes.body.payState == 2) {
                  this.$notify({
                    title: '支付成功',
                    message: '您的支付已经成功，请查看账户余额'
                  })
                  this.payDialog = false
                  this.qrCode = ''
                  this.outTradeNo = ''
                  this.isLoading = false
                  clearInterval(this.payInterval)
                  this.getMoney()
                }
                if (payRes.body.payState == 1) {
                  this.$message.error('支付失败 ，请重新支付')
                  this.payDialog = false
                  this.qrCode = ''
                  this.outTradeNo = ''
                  this.isLoading = false
                  clearInterval(this.payInterval)
                }
              })

            if (this.payIntervalCount > 60) {
              this.$message.error('支付订单已超时 ，请重新支付')
              this.payDialog = false
              this.qrCode = ''
              this.outTradeNo = ''
              this.isLoading = false
              clearInterval(this.payInterval)
            }
            this.payIntervalCount++
          }, 3000)
        } else if (res.code === 1001 && res.body.wechat_code) {
          // 有二维码，当面付
          this.qrCode = res.body.wechat_code
          console.log(this.qrCode)
          this.codeUrl = await QRCode.toDataURL(this.qrCode, options)
          this.outTradeNo = res.body.out_trade_no
          this.payDialog = true
          // 在这里轮询
          this.payInterval = setInterval(() => {
            this.$axios
              .get('/finance/rechargeRecord/queryPayStateFk', {
                params: {
                  paySn: this.outTradeNo
                }
              })
              .then((payRes) => {
                if (payRes.body.payState == 2) {
                  this.$notify({
                    title: '支付成功',
                    message: '您的支付已经成功，请查看账户余额'
                  })
                  this.payDialog = false
                  this.qrCode = ''
                  this.outTradeNo = ''
                  this.isLoading = false
                  clearInterval(this.payInterval)
                  this.getMoney()
                }
                if (payRes.body.payState == 1) {
                  this.$message.error('支付失败 ，请重新支付')
                  this.payDialog = false
                  this.qrCode = ''
                  this.outTradeNo = ''
                  this.isLoading = false
                  clearInterval(this.payInterval)
                }
              })

            if (this.payIntervalCount > 60) {
              this.$message.error('支付订单已超时 ，请重新支付')
              this.payDialog = false
              this.qrCode = ''
              this.outTradeNo = ''
              this.isLoading = false
              clearInterval(this.payInterval)
            }
            this.payIntervalCount++
          }, 3000)
        } else {
          this.$message.error(res.msg || '请求支付失败，请稍后重试')
          this.isLoading = false
        }
      }
    },

    handleClosePayCode () {
      this.payDialog = false
      this.isLoading = false
      clearInterval(this.payInterval)
    },

    async doRechargeOther(){
      if (this.cardNo.length != 32) {
        return this.$message.error('请输入正确位数的卡号')
      }
      const res = await this.$axios.post(`finance/rechargeCard/use`,{cardNo:this.cardNo})
      if (res.code === 1001) {
        this.cardNo = ''
        this.$notify({
          title: '支付成功',
          message: '您的支付已经成功，请查看账户余额'
        })
        location.href = '/main?pay=1'
      }else{

        this.$message.error(res.msg);
        this.cardNo = ''
      }

    }
  }
}
</script>

<style lang="scss" scoped>
@import 'assets/style/layer.css';
@import 'assets/style/layui.css';
@import 'assets/style/style4/common.css';
@import 'assets/style/style4/openlogin.css';
@import 'assets/style/style4/style.css';
@import 'assets/style/style4/font_1451715_0505c2bxv7b7.css';
@import 'element-ui/lib/theme-chalk/index.css';
section {
  padding: 0 15px 30px 15px;
  background: white;
}
.el-tab-pane {
  padding: 15px;
}
.row {
  & > span:first-child {
    width: 100px;
    font-size: 14px;
    text-align: right;
    line-height: 40px;
    display: inline-block;
  }
  & + .row {
    margin-top: 15px;
  }
  .remind {
    font-size: 14px;
    display: inline-block;
    width: calc(100% - 80px);
    vertical-align: text-top;
    margin-left: 100px;
    p + p {
      margin-top: 10px;
    }
  }
  .el-input {
    width: 200px;
  }
}
.charge-pay {
  display: inline-block;
  vertical-align: middle;
  li {
    width: 75px;
    height: 50px;
    box-sizing: border-box;
    display: inline-block;
    vertical-align: top;
    border: 1px solid $--basic-border-color;
    img {
      object-fit: contain;
    }
    &:hover {
      cursor: pointer;
      border: 1px solid $--color-primary;
    }
    &.selected {
      border: 1px solid $--color-primary;
    }
  }
  li + li {
    margin-left: 15px;
  }
}
.third-tip {
  padding: 10px 15px;
  font-size: 12px;
  color: $--basic-orange;
  border: 1px dashed $--basic-orange;
}
.el-button {

}
.userrecharge-box {
  .layui-form-label {
    min-width: 100px;
  }
  .choosepay-way {
    display: flex;
    margin-left: 0;
  }
  .payitems {
    position: relative;
    border: 1px solid #f1f0f4;
    border-radius: 3px;
    overflow: hidden;
    display: inline-block;
    float: left;
    cursor: pointer;
    margin-right: 20px;
  }
  .payitems-active {
    border: 1px solid #ff0000;
  }
}
</style>
<style>
.goodsinfo-container .el-dialog__body {
  padding-top: 0;
}
</style>
